package com.jp.knowledge.fragment;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.dialog.LoadingDialog;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.PayActivity;
import com.jp.knowledge.activity.PayIntegralActivity;
import com.jp.knowledge.activity.TeamCircleMessageActivity;
import com.jp.knowledge.activity.TeamCircleShowDetailActivity;
import com.jp.knowledge.adapter.team_circle.TeamCircleAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.TeamCircleCommentBar;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InteractDataModel;
import com.jp.knowledge.model.TeamCircleModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.service.LatestStateService;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

public class TeamCircleDataShowFragment extends Fragment implements View.OnClickListener,
		TeamCircleAdapter.TeamCircleViewClickListener,
		CanRefreshLayout.OnRefreshListener,
		CanRefreshLayout.OnLoadMoreListener,
		ResultSubscriber.OnResultListener,
		TeamCircleFragment.FragmentCallBack {

	protected static final int MODE_0 = 0x00;          // 下拉刷新
	protected static final int MODE_1 = 0x01;          // 加载更多
	private static final int PRAISE = 0x02;            // 点赞
	protected static final int COMMENT = 0x03;         // 评论
	private static final int PAY_REWARD = 0x04;        // 打赏
	protected static final int DELETE = 0x05;          // 删除

	protected View contentView;
	protected CanRefreshLayout canRefreshLayout;
	private NestedScrollView nestedScrollView;
	private RecyclerView teamCircleRv;
	private JpRefreshView footerView;
	protected LinearLayout teamCircleHeader;
	protected ImageView converImg;
	protected LinearLayout remindView;
	private ImageView remindIcon;
	private TextView remindText;
	protected CommDialog deleteDialog;
	private Dialog contentLongClickDialog;
	private LoadingDialog loadingDialog;

	private volatile int scrollY;
	protected Context context;
	private int type;
	private String companyId;
	private int companyType;
	private String companyName;
	private int auditStete;
	private String cover;
	protected TeamCircleAdapter teamCircleAdapter;
	protected List<TeamCircleModel> teamCircleModels;
	private boolean isVisible;
	private ClipboardManager clipboardManager;
	private FileCacheManager cacheManager;
	protected String cachePath;

	private TeamCircleCommentBar bottomCommentBar;
	private BroadcastReceiver broadcaseReciver;
	protected LocalBroadcastManager localBroadcastManager;

	public TeamCircleDataShowFragment newInstance(String companyId,
												  int companyType,
												  String companyName,
												  int auditStete,
												  int type,
												  String cover) {
		this.companyId = companyId;
		this.companyName = companyName;
		this.companyType = companyType;
		this.auditStete = auditStete;
		this.type = type;
		this.cover = cover;
		this.isVisible = false;
		return this;
	}

	public String getCompanyId() {
		return companyId;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (contentView == null) {
			context = getContext();
			contentView = View.inflate(context, R.layout.fragment_team_circle, null);
			init();
		}
		return contentView;
	}

	@Override
	public void onDestroy() {
		localBroadcastManager.unregisterReceiver(broadcaseReciver);
		saveDataToCache();
		super.onDestroy();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode != PAY_REWARD || resultCode != RESULT_OK || data == null)
			return;
		String scoopId = data.getStringExtra("scoopId");
		String userId = data.getStringExtra("userId");
		if (scoopId == null || userId == null)
			return;
		for (int i = 0; i < teamCircleModels.size(); i++) {
			TeamCircleModel teamCircleModel = teamCircleModels.get(i);
			if (!scoopId.equals(teamCircleModel.getId()) || !userId.equals(teamCircleModel.getUserId()))
				continue;
			List<TeamCircleModel.PraiseBean> payBeans = teamCircleModel.getPayList();
			if (payBeans == null) {
				payBeans = new ArrayList<>();
				teamCircleModel.setPayList(payBeans);
			}
			teamCircleModel.setIsPay(1);
			TeamCircleModel.PraiseBean payBean = new TeamCircleModel.PraiseBean();
			try {
				UserData userData = ((JpApplication) getActivity().getApplication()).getUserData();
				payBean.setUid(userData.getUuid());
				payBean.setPortrait(userData.getPortrait());
				payBean.setNickname(userData.getNickname());
			} catch (Exception e) {
				payBean.setUid("");
				payBean.setPortrait("");
				payBean.setNickname("");
			}
			payBeans.add(payBean);
			teamCircleAdapter.notifyItemChanged(i);
			return;
		}
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		this.isVisible = isVisibleToUser;
	}

	private void init() {
		initView();

//        if(auditStete != 1) {
//            contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.VISIBLE);
//            canRefreshLayout.setVisibility(View.GONE);
//            String remindText = "你加入的\n";
//            if(companyName == null || companyName.trim().length() == 0)
//                remindText += "组织\n";
//            else
//                remindText += (companyName + "\n");
//            if(auditStete == 0)
//                remindText += "正在审核中，暂时无法使用团队圈";
//            else
//                remindText += "没有通过审核，尝试更查看其它组织";
//            ((TextView)contentView.findViewById(R.id.team_circle_empty_text)).setText(remindText);
//            return;
//        }

		initWeChatBroadcastReceiver();

		teamCircleModels = new ArrayList<>();
		clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
		cacheManager = new FileCacheManager();
		initCachePath();
		readDataFromCache();
	}

	protected void initView() {
		this.canRefreshLayout = (CanRefreshLayout) contentView.findViewById(R.id.refresh);
		this.nestedScrollView = (NestedScrollView) contentView.findViewById(R.id.can_content_view);
		this.teamCircleRv = (RecyclerView) contentView.findViewById(R.id.team_circle_data_rv);
		this.footerView = (JpRefreshView) contentView.findViewById(R.id.can_refresh_footer);
		this.teamCircleHeader = (LinearLayout) contentView.findViewById(R.id.team_circle_header);
		this.converImg = (ImageView) contentView.findViewById(R.id.team_circle_conver);
		this.remindView = (LinearLayout) contentView.findViewById(R.id.team_circle_remind_view);
		this.remindIcon = (ImageView) contentView.findViewById(R.id.team_circle_remind_icon);
		this.remindText = (TextView) contentView.findViewById(R.id.team_circle_remind_text);
		this.remindView.setOnClickListener(this);

		initDialog();

		teamCircleRv.setHasFixedSize(true);
		teamCircleRv.setLayoutManager(new LinearLayoutManager(context) {
			@Override
			public boolean canScrollVertically() {
				return false;
			}
		});
		teamCircleRv.addItemDecoration(new JpDiver(context));
		initAdapter();
		teamCircleAdapter.setViewClickListener(this);
		teamCircleRv.setAdapter(teamCircleAdapter);
		canRefreshLayout.setOnRefreshListener(this);
		canRefreshLayout.setOnLoadMoreListener(this);
		updateRemindView();
	}

	private void initDialog() {
		deleteDialog = new CommDialog(context);
		deleteDialog.setContent(getString(R.string.team_circle_delete_remind));
		deleteDialog.setLeft(getString(R.string.team_circle_delete_left));
		deleteDialog.setRight(getString(R.string.team_circle_delete_right));
		deleteDialog.setRightListener(this);

		contentLongClickDialog = new Dialog(context, R.style.custom_idalgo);
		View longClickDialogView = View.inflate(context, R.layout.team_circle_content_long_click_dialog, null);
		longClickDialogView.findViewById(R.id.team_circle_content_copy).setOnClickListener(this);
		contentLongClickDialog.setContentView(longClickDialogView);
		loadingDialog = new LoadingDialog(context);

		bottomCommentBar = new TeamCircleCommentBar(context);
		bottomCommentBar.setOnBottomBarListener(new TeamCircleCommentBar.OnBottomBarListener() {
			@Override
			public void onDismiss() {
			}

			@Override
			public void onCommentCommit(String content) {
				commitComment(content, (int) bottomCommentBar.getTag());
			}
		});
	}

	private void initWeChatBroadcastReceiver() {
		localBroadcastManager = LocalBroadcastManager.getInstance(context);
		broadcaseReciver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (PayActivity.WECHAT_PAY_SUCCESS.equals(action)) {
					int errorCode = intent.getIntExtra(PayActivity.WECHAT_PAY_ERR_CODE, -1);
					int type = intent.getIntExtra(PayActivity.WECHAT_PAY_TYPE, -1);
					String scoopId = intent.getStringExtra(PayActivity.WECHAT_PAY_SCOOP_ID);
					String userId = intent.getStringExtra(PayActivity.WECHAT_PAY_USER_ID);
					String userName = intent.getStringExtra(PayActivity.WECHAT_PAY_USER_NAME);
					String userIcon = intent.getStringExtra(PayActivity.WECHAT_PAY_USER_ICON);
					if (errorCode != BaseResp.ErrCode.ERR_OK || type != 16 || scoopId == null || userId == null
							|| teamCircleModels == null || teamCircleModels.size() == 0)
						return;
					for (int i = 0; i < teamCircleModels.size(); i++) {
						TeamCircleModel teamCircleModel = teamCircleModels.get(i);
						if (!scoopId.equals(teamCircleModel.getId()) || !userId.equals(teamCircleModel.getUserId()))
							continue;
						List<TeamCircleModel.PraiseBean> payBeans = teamCircleModel.getPayList();
						if (payBeans == null) {
							payBeans = new ArrayList<>();
							teamCircleModel.setPayList(payBeans);
						}
						teamCircleModel.setIsPay(1);
						TeamCircleModel.PraiseBean payBean = new TeamCircleModel.PraiseBean();
						try {
							UserData userData = ((JpApplication) getActivity().getApplication()).getUserData();
							payBean.setUid(userData.getUuid());
							payBean.setPortrait(userData.getPortrait());
							payBean.setNickname(userData.getNickname());
						} catch (Exception e) {
							payBean.setUid("");
							payBean.setPortrait("");
							payBean.setNickname("");
						}
						payBeans.add(payBean);
						teamCircleAdapter.notifyItemChanged(i);
						return;
					}
				} else if (LocalBroadCast.USER_DATA_CHANGE.equals(action)) {
					canRefreshLayout.autoRefresh();
				} else if (LocalBroadCast.GET_INTERACT_DATA_CODE.equals(action)) {
					updateRemindView();
				} else if (LocalBroadCast.TEAM_CIRCLE_DATA_CHANGE.equals(action)) {
					TeamCircleModel data = (TeamCircleModel) intent.getSerializableExtra("data");
					if (data == null || data.getId() == null || teamCircleModels == null)
						return;
					for (int i = 0; i < teamCircleModels.size(); i++) {
						if (data.getId().equals(teamCircleModels.get(i).getId())) {
							data.setShowAll(teamCircleModels.get(i).isShowAll());
							teamCircleModels.set(i, data);
							teamCircleAdapter.updateAdapter(teamCircleModels);
							return;
						}
					}
				} else if (LocalBroadCast.TEAM_CIRCLE_DATA_DELETE.equals(action)) {
					String scoopId = intent.getStringExtra("scoopId");
					if (scoopId == null || scoopId.trim().length() == 0 || teamCircleModels == null)
						return;
					for (TeamCircleModel teamCircleModel : teamCircleModels) {
						if (scoopId.equals(teamCircleModel.getId())) {
							teamCircleModels.remove(teamCircleModel);
							teamCircleAdapter.updateAdapter(teamCircleModels);
							if (teamCircleModels == null || teamCircleModels.size() == 0)
								contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.VISIBLE);
							else
								contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.GONE);
							return;
						}
					}
				}
			}
		};
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(PayActivity.WECHAT_PAY_SUCCESS);
		intentFilter.addAction(LocalBroadCast.USER_DATA_CHANGE);
		intentFilter.addAction(LocalBroadCast.GET_INTERACT_DATA_CODE);
		intentFilter.addAction(LocalBroadCast.TEAM_CIRCLE_DATA_CHANGE);
		intentFilter.addAction(LocalBroadCast.TEAM_CIRCLE_DATA_DELETE);
		localBroadcastManager.registerReceiver(broadcaseReciver, intentFilter);
	}

	protected void initCachePath() {
		cachePath = getContext().getCacheDir().getPath() + "/team_circle_" + type;
		UserData userData = ((JpApplication) getActivity().getApplication()).getUserData();
		if (userData != null)
			cachePath += ("_" + userData.getUuid());
		cachePath += "_" + companyId + ".dat";
	}

	protected void initAdapter() {
		teamCircleAdapter = new TeamCircleAdapter(context, teamCircleModels);
		teamCircleAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
			@Override
			public void itemSelect(int position) {
				startActivity(new Intent(context, TeamCircleShowDetailActivity.class)
						.putExtra("id", teamCircleModels.get(position).getId()));
			}
		});
	}

	protected void updateRemindView() {
		InteractDataModel interactDataModel = LatestStateService.getInteractDataModel();
		if (interactDataModel == null) {
			remindView.setVisibility(View.GONE);
			return;
		}
		List<InteractDataModel.ListBean> listBeen = interactDataModel.getList();
		if (listBeen == null || listBeen.size() == 0) {
			remindView.setVisibility(View.GONE);
			return;
		}
		for (InteractDataModel.ListBean listBean : listBeen) {
			if (companyId != null && companyId.equals(listBean.getCompanyId())) {
				if (listBean.getCount() > 0) {
					remindView.setVisibility(View.VISIBLE);
					ImageLoadUtil.load(context, listBean.getPortrait(), remindIcon);
					remindText.setText(listBean.getCount() + "条新消息");
				} else {
					remindView.setVisibility(View.GONE);
				}
				return;
			}
		}
		remindView.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.right_btn:                     // 删除对话右按钮
				doDelete((int) deleteDialog.getTag());
				break;
			case R.id.team_circle_content_copy:     // 复制内容
				clipboardManager.setText(teamCircleModels.get((int) teamCircleRv.getTag()).getContent());
				toastMsg("内容已复制到剪切板");
				contentLongClickDialog.dismiss();
				break;
			case R.id.team_circle_remind_view:
				startActivity(new Intent(context, TeamCircleMessageActivity.class)
						.putExtra("companyId", companyId)
						.putExtra("companyType", companyType));
				LatestStateService.clearCompanyMsg(companyId);
				break;
		}
	}

	@Override
	public void onStart(int requestType) {
	}

	@Override
	public void onCompleted(int requestType) {
	}

	@Override
	public void onError(int requestType) {
		switch (requestType % 10) {
			case MODE_0:            // 刷新数据
			case MODE_1:            // 加载更多
//                toastMsg(R.string.team_circle_data_load_err);
				canRefreshLayout.refreshComplete();
				canRefreshLayout.loadMoreComplete();
				break;
			case PRAISE:            // 点赞
				if (teamCircleModels.get(requestType / 10).getIsPraise() == 0) {
					List<TeamCircleModel.PraiseBean> praises = teamCircleModels.get(requestType / 10).getPraise();
					praises.remove(0);
				}
//                toastMsg(R.string.team_circle_operation_fail);
				teamCircleAdapter.notifyItemChanged(requestType / 10);
				break;
			case COMMENT:           // 评论
				List<TeamCircleModel.CommentsBean> comments = teamCircleModels.get(requestType / 10).getComments();
				comments.remove(comments.size() - 1);
//                toastMsg(R.string.team_circle_comment_fail);
				teamCircleAdapter.notifyItemChanged(requestType / 10);
				break;
			case PAY_REWARD:        // 打赏
				break;
			case DELETE:             // 删除
//                toastMsg(R.string.team_circle_delete_fail);
				loadingDialog.cancel();
				break;
		}
		onCompleted(requestType);
	}

	@Override
	public void onNext(IModel data, int requestType) {
		if (data.getErrcode() != 0) {
			toastMsg(data.getMessage());
			onError(requestType);
			return;
		}
		switch (requestType % 10) {
			case MODE_0:            // 刷新数据
			case MODE_1:            // 加载更多
				List<TeamCircleModel> tmpDatas = data.getList(TeamCircleModel.class);
				if (tmpDatas == null)
					tmpDatas = new ArrayList<>();
				if (requestType % 10 == MODE_0) {
					footerView.setLoadComplete(false);
					teamCircleModels = tmpDatas;
					if (tmpDatas.size() == 0) {
//                        toastMsg("团队圈暂无更新");
					} else {
//                        toastMsg(String.format(getString(R.string.team_circle_update), tmpDatas.size()));
					}
				} else if (requestType % 10 == MODE_1) {
					if (tmpDatas.size() == 0) {
						footerView.setLoadComplete(true);
//                        toastMsg("暂无更多数据");
					} else {
						teamCircleModels.addAll(tmpDatas);
//                        toastMsg(String.format(getString(R.string.team_circle_load), tmpDatas.size()));
					}
				}
				canRefreshLayout.refreshComplete();
				canRefreshLayout.loadMoreComplete();
				if (teamCircleModels == null || teamCircleModels.size() == 0)
					contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.VISIBLE);
				else
					contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.GONE);
				teamCircleAdapter.updateAdapter(teamCircleModels);
				break;
			case PRAISE:            // 点赞
//                // 当前用户已经点赞则取消点赞
//                int isPraise = teamCircleModels.get(requestType/10).getIsPraise();
//                if(isPraise == 1) {
//                    isPraise = 0;
//                    List<TeamCircleModel.PraiseBean> praises = teamCircleModels.get(requestType/10).getPraise();
//                    for (TeamCircleModel.PraiseBean praise : praises) {
//                        if (praise != null && praise.getUid() != null
//                                && praise.getUid().equals(userData.getUuid())) {
//                            praises.remove(praise);
//                            break;
//                        }
//                    }
//                } else{
//                    isPraise = 1;
//                }
//                teamCircleModels.get(requestType/10).setIsPraise(isPraise);
//                teamCircleAdapter.notifyItemChanged(requestType/10);
				break;
			case COMMENT:           // 评论
//                toastMsg(R.string.team_circle_comment_success);
				break;
			case PAY_REWARD:        // 打赏
				break;
			case DELETE:             // 删除
//                toastMsg(R.string.team_circle_delete_success);
				teamCircleModels.remove(requestType / 10);
				teamCircleAdapter.updateAdapter(teamCircleModels);
				if (teamCircleModels.size() == 0)
					contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.VISIBLE);
				else
					contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.GONE);
				loadingDialog.cancel();
				break;
		}
	}

	@Override
	public void onRefresh() {
		getData(type, MODE_0);
	}

	@Override
	public void onLoadMore() {
		if (footerView.isLoadComplete())
			canRefreshLayout.loadMoreComplete();
		else
			getData(type, MODE_1);
	}

	/* 点击 Item 时触发的事件处理 */
	@Override
	public void onItemDeleteClick(int position) {
		deleteDialog.setTag(position);
		deleteDialog.show();
	}

	@Override
	public void onCommentItemClick(int parentPosition, int position) {
		showCommitBar(teamCircleModels.get(parentPosition).getComments().get(position).getUid(),
				teamCircleModels.get(parentPosition).getComments().get(position).getNickname(), parentPosition);
	}

	@Override
	public void onPayRewardClick(int position) {
		TeamCircleModel teamCircleModel = teamCircleModels.get(position);
		if (teamCircleModel.getIsPay() == 1)
			toastMsg("你已经打赏过了，请勿重复打赏");
		else
//            PayActivity.gotoPay(getContext(), teamCircleModel.getId(), teamCircleModel.getUserId(), 16,
//                    teamCircleModel.getNickname(), teamCircleModel.getPortrait());
			startActivityForResult(new Intent(context, PayIntegralActivity.class)
					.putExtra("scoopId", teamCircleModel.getId())
					.putExtra("userId", teamCircleModel.getUserId())
					.putExtra("userName", teamCircleModel.getNickname())
					.putExtra("userIcon", teamCircleModel.getPortrait()), PAY_REWARD);
	}

	@Override
	public void onPraiseClick(int position) {
		commitPraise(teamCircleModels.get(position).getIsPraise() == 1 ? false : true, position);
	}

	@Override
	public void onCommentClick(int position) {
		showCommitBar(teamCircleModels.get(position).getId(), null, position);
	}

	@Override
	public void onContextLongClick(int position) {
		teamCircleRv.setTag(position);
		contentLongClickDialog.show();
	}

	/* 获取数据 */
	protected void getData(int type, int mode) {
		long time = System.currentTimeMillis();
		if (teamCircleModels != null && teamCircleModels.size() > 0 && mode == MODE_1) {
			time = teamCircleModels.get(teamCircleModels.size() - 1).getTime();
		}
		JsonObject param = new JsonObject();
		param.addProperty("token", HttpHelper.token);
		if (companyType == 2) {       // 学校使用classId
			List<OrganizaModel> companyList = new ArrayList<>();
			try {
				companyList.addAll(((JpApplication) getActivity().getApplication()).getUserData().getCompanyList());
			} catch (Exception e) {
			} finally {
				for (OrganizaModel organizaModel : companyList) {
					if (organizaModel.getCompanyId().equals(companyId)) {
						param.addProperty("companyId", organizaModel.getClassId());
						break;
					}
				}
			}
		} else {
			param.addProperty("companyId", companyId);
		}
		param.addProperty("companyType", companyType);
		param.addProperty("type", type);
		param.addProperty("time", time);
		param.addProperty("mode", mode);
		HttpHelper.getInstance(context).getTeamCircle(param, mode, this);
	}

	/* 发布评论 */
	protected void commitComment(String content, int position) {
		TeamCircleModel.CommentsBean comment = new TeamCircleModel.CommentsBean();
		comment.setCommentType(3);
		comment.setContent(content);
		try {
			UserData userData = ((JpApplication) getActivity().getApplication()).getUserData();
			comment.setNickname(userData.getUsername());
			comment.setUid(userData.getUuid());
		} catch (Exception e) {
		}
		TeamCircleModel.CommentsBean.ReplyBean replyBean = new TeamCircleModel.CommentsBean.ReplyBean();
		replyBean.setUid(toUid);
		replyBean.setNickname(toNickName);
		comment.setReply(replyBean);

		JsonObject param = new JsonObject();
		param.addProperty("token", HttpHelper.token);
		param.addProperty("content", comment.getContent());
		param.addProperty("id", teamCircleModels.get(position).getId());
		param.addProperty("toUid", comment.getReply().getUid());
		HttpHelper.getInstance(context)
				.teamCircleComment(param, position * 10 + COMMENT, TeamCircleDataShowFragment.this);

		teamCircleModels.get(position).getComments().add(comment);
		teamCircleAdapter.notifyItemChanged(position);
	}

	/* 提交点赞 */
	private void commitPraise(boolean isPraise, int position) {

		TeamCircleModel.PraiseBean praiseBean = new TeamCircleModel.PraiseBean();
		try {
			UserData userData = ((JpApplication) getActivity().getApplication()).getUserData();
			praiseBean.setUid(userData.getUuid());
			praiseBean.setNickname(userData.getNickname());
			praiseBean.setPortrait(userData.getPortrait());
		} catch (Exception e) {
		}

		JsonObject param = new JsonObject();
		param.addProperty("token", HttpHelper.token);
		param.addProperty("id", teamCircleModels.get(position).getId());
		param.addProperty("type", isPraise ? 1 : 0);
		HttpHelper.getInstance(context)
				.teamCirclePraise(param, position * 10 + PRAISE, this);

		if (isPraise) {
			teamCircleModels.get(position).getPraise().add(0, praiseBean);
		} else {
			TeamCircleModel teamCircleModel = teamCircleModels.get(position);
			List<TeamCircleModel.PraiseBean> praiseBeanList = teamCircleModel.getPraise();
			for (TeamCircleModel.PraiseBean praiseBean1 : praiseBeanList)
				if (praiseBean1.getUid().equals(praiseBean.getUid())) {
					praiseBeanList.remove(praiseBean1);
					break;
				}
		}
		teamCircleModels.get(position).setIsPraise(isPraise ? 1 : 0);
		teamCircleAdapter.notifyItemChanged(position);
	}

	/* 删除 */
	protected void doDelete(int position) {
		JsonObject param = new JsonObject();
		param.addProperty("token", HttpHelper.token);
		param.addProperty("id", teamCircleModels.get(position).getId());
		HttpHelper.getInstance(context)
				.teamCircleDelete(param, position * 10 + DELETE, this);
		deleteDialog.cancel();
		loadingDialog.show();

//        teamCircleModels.remove(teamCircleAdapter.getClickIndex());
//        teamCircleAdapter.notifyDataSetChanged();
//        if (teamCircleModels.size() == 0)
//            contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.VISIBLE);
//        else
//            contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.GONE);
	}

	private void toastMsg(String msg) {
		if (!this.isVisible)
			return;
		ToasUtil.toast(context, msg);
	}

	protected String toUid;
	protected String toNickName;

	private void showCommitBar(String toUid, String toNickName, final int position) {
		this.toUid = toUid;
		this.toNickName = toNickName;

		if (toNickName == null)
			bottomCommentBar.setHint(getString(R.string.team_circle_comment));
		else
			bottomCommentBar.setHint(getString(R.string.team_circle_reply) + toNickName);
		bottomCommentBar.setTag(position);
		bottomCommentBar.show();

		teamCircleRv.postDelayed(new Runnable() {
			@Override
			public void run() {
				View clickItem = teamCircleRv.getLayoutManager().getChildAt(position);
				int[] position = new int[2];
				clickItem.getLocationOnScreen(position);
				int itemBottomY = position[1] + clickItem.getHeight();
				int commentBarY = bottomCommentBar.getPositionY();
				nestedScrollView.smoothScrollBy(0, itemBottomY-commentBarY);
			}
		}, 800);
	}

	@Override
	public void refreshData() {
		if (contentView == null)
			return;
		nestedScrollView.smoothScrollTo(0, 0);
		canRefreshLayout.autoRefresh();
	}

	/* 读取缓存 */
	protected void readDataFromCache() {
		Observable.create(new Observable.OnSubscribe<List<TeamCircleModel>>() {
			@Override
			public void call(Subscriber<? super List<TeamCircleModel>> subscriber) {
				teamCircleModels = (List<TeamCircleModel>) cacheManager.readObject(cachePath);
				subscriber.onNext(teamCircleModels);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<List<TeamCircleModel>>() {
					@Override
					public void onCompleted() {
						if (teamCircleAdapter.getItemCount() == 0) {
							contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.VISIBLE);
							canRefreshLayout.autoRefresh();
						} else {
							contentView.findViewById(R.id.team_circle_empty_bg).setVisibility(View.GONE);
							getData(type, MODE_0);
						}
					}

					@Override
					public void onError(Throwable e) {
						onCompleted();
					}

					@Override
					public void onNext(List<TeamCircleModel> list) {
						converImg.setVisibility(View.VISIBLE);
						converImg.getLayoutParams().height = (int) (DensityUtil.getScreenWidth() * 302f / 922f + 0.5f);
						if (cover != null && cover.trim().length() > 0)
							ImageLoadUtil.load(context, cover, converImg);
						else
							converImg.setImageResource(R.mipmap.imaging);
						teamCircleAdapter.updateAdapter(teamCircleModels);
						if(scrollY > 0) {
							nestedScrollView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
								@Override
								public boolean onPreDraw() {
									nestedScrollView.getViewTreeObserver().removeOnPreDrawListener(this);
									nestedScrollView.scrollTo(0, scrollY);
									scrollY = 0;
									return false;
								}
							});
						}
					}
				});
	}

	/* 缓存数据 */
	protected void saveDataToCache() {
		if (teamCircleModels == null)
			teamCircleModels = new ArrayList<>();
		int size = teamCircleModels.size();
		final List<TeamCircleModel> saveData = new ArrayList<>();
		if (size > 50)  // 最多保存 50 条数据
			for (int i = 0; i < 50; i++)
				saveData.add(teamCircleModels.get(i));
		else
			saveData.addAll(teamCircleModels);
		new Thread(new Runnable() {
			@Override
			public void run() {
				cacheManager.wirteObject(saveData, cachePath);
			}
		}).start();
	}

	public int getScrollY() {
		if(nestedScrollView != null)
			return nestedScrollView.getScrollY();
		return scrollY;
	}

	public void setScrollY(int scrollY) {
		if(nestedScrollView != null)
			nestedScrollView.scrollTo(0, scrollY);
		else
			this.scrollY = scrollY;
	}
}